package com.summer.safe.controller.system;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.summer.safe.config.properties.ConfigureProperties;
import com.summer.safe.entity.Upload;
import com.summer.safe.utils.DateUtils;
import com.summer.safe.utils.FileUtils;
import com.summer.safe.utils.Global;
import com.summer.safe.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Paths;
import java.util.*;



/**文件的传输和下载
 * @author lm
 */

@RestController
@RequestMapping(value = "/upload")
public class UploadController {

    @Resource
    private ConfigureProperties configureProperties;
    private JSONObject result = null;


    //目录
    private String pathresult = "";

    //文件的名称
    private String fileName="";
    /**
     * 文档的上传
     */
    @RequestMapping(value = "/file", method = RequestMethod.POST)
    @ResponseBody
        public Object file(@RequestParam("file") MultipartFile file) throws IOException {

            int num=1;


            Upload upload = new Upload();

            //判断文件是否为空
            if (!file.isEmpty()) {

                //得到文件的名称
                fileName = file.getOriginalFilename();
                //文件的路径
                String pathname = "";

                //获得文件的类型  根据文件类型创建文件夹
                String fileType = file.getContentType().split("/")[0];
                fileType = "image,audio,video".contains(fileType) ? fileType : "file";

                String rootPath = configureProperties.getFileUploadPath();
                //获得完整的文件夹
                String descDirNames =  Global.UPLOAD_FILES + fileType + "/" + UserUtils.getUser().getId()+ "/";
                FileUtils.createDirectory(rootPath + descDirNames);
                pathresult= rootPath + descDirNames;
                //文件存在的地址
                pathname = pathresult + fileName;
                boolean existence = this.existencefile(pathname);

                if(existence==true){
                    for(int i=0;i<num;i++){
                        num++;
                        //用于生成新的文件名称
                        pathname = this.rendname(fileName,i);
                        existence= this.existencefile(pathname);
                        //判读文件是否存在
                        if(existence==false){
                            //获得新的文件名称
                            String name=pathname.substring(pathname.lastIndexOf("/")+1,pathname.length());
                            fileName=name;
                            break;
                        }
                    }
                }
                //类型
                upload.setFileType(fileType);
                //名称
                upload.setFileName(fileName);
                //地址
                upload.setFilePath("/"+descDirNames + fileName);
                //大小
                upload.setSize(file.getSize());

                //保存文件
                this.FileInputStream(file.getInputStream(), pathname);
                upload.setCode(0);
                upload.setMsg("文件上传成功了");
                return JSONArray.toJSON(upload);




            } else {
                upload.setCode(1);
                upload.setMsg("文件出现问题，请检查文件后发送");
                return JSONArray.toJSON(upload);
            }
        }

        /**
         * 图片上传，手机端(目前用于微信端)
         */
        @RequestMapping(value = "/mob/file", method = RequestMethod.POST)
        @ResponseBody
        public Object fileMobile(@RequestParam("file") MultipartFile file) throws IOException {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            String userID = attributes.getRequest().getParameter("user");
            userID = StringUtils.isEmpty(userID)?"未知用户":userID;
            Upload upload = new Upload();
            //判断文件是否为空
            if (!file.isEmpty()) {
                //得到文件的名称
                String fileName = file.getOriginalFilename();
                //文件的路径
                String pathname = "";

                //获得文件的类型  根据文件类型创建文件夹
                String fileType = file.getContentType().split("/")[0];
                fileType = "image,audio,video".contains(fileType) ? fileType : "file";

                String rootPath = configureProperties.getFileUploadPath();
                //获得完整的文件夹
                String descDirNames = Global.UPLOAD_FILES+"mobile/"  + fileType + "/weixin/" + userID+ "/" + DateUtils.getDate("yyyyMMddHH");
                //创建目录
                FileUtils.createDirectory(rootPath + descDirNames);

                //文件存在的地址
                pathname = rootPath + descDirNames + "/" + fileName;

                //保存文件
                this.FileInputStream(file.getInputStream(), pathname);

                upload.setFileType(fileType);
                upload.setFileName(fileName);
                upload.setCode(0);
                upload.setMsg("文件上传成功了");
                upload.setFilePath(descDirNames + "/" + fileName);
                upload.setSize(file.getSize());
                return JSONArray.toJSON(upload);
            } else {
                upload.setCode(1);
                upload.setMsg("文件出现问题，请检查文件后发送");
                return JSONArray.toJSON(upload);
            }
        }

        /**
         * 多文档的上传 (用于APP上传图片)
         */
        @RequestMapping(value = "/mob/app/files")
        @ResponseBody
        public String files(@RequestParam("files") MultipartFile[] files)  throws IOException {
            List<Upload> uploadList = new ArrayList<>();
            for(int i = 0;i<files.length;i++){
                Upload upload = new Upload();
                MultipartFile file = files[i];
                //判断文件是否为空
                if (!file.isEmpty()) {
                    //得到文件的名称
                    String fileName = file.getOriginalFilename();
                    //文件的路径
                    String pathname = "";

                    //获得文件的类型  根据文件类型创建文件夹
                    String fileType = file.getContentType().split("/")[0];
                    fileType = "image,audio,video".contains(fileType) ? fileType : "file";

                    String rootPath = configureProperties.getFileUploadPath();
                    //获得完整的文件夹
                    String descDirNames = "uploadfiles/mobile/app" + "/" + fileType + "/" + UserUtils.getUser().getId()  + "/" + DateUtils.getDate("yyyyMMddHH");
                    //创建目录
                    FileUtils.createDirectory(rootPath + descDirNames);

                    //文件存在的地址
                    pathname = rootPath + descDirNames + "/" + fileName;

                    //保存文件
                    this.FileInputStream(file.getInputStream(), pathname);

                    upload.setFileType(fileType);
                    upload.setFileName(fileName);
                    upload.setCode(0);
                    upload.setMsg("文件上传成功了");
                    upload.setFilePath(descDirNames + "/" + fileName);
                    upload.setSize(file.getSize());

                } else {
                    upload.setCode(1);
                    upload.setMsg("文件出现问题，请检查文件后发送");
                }
                uploadList.add(upload);

            }
            return JSONObject.toJSONString(uploadList);
        }


        /**
         * 文件保存
         *
         * @param stream
         * @param filePath
         *
         */
        public void FileInputStream(InputStream stream, String filePath){
            File file=new File(filePath);
            //判断上传文件是否存在，如果已存在则删除
            if (file.exists()) {
                FileUtils.deleteFile(filePath);
            }

            FileOutputStream fs = null;
            try{
                fs = new FileOutputStream(filePath);
                byte[] buffer = new byte[1024];
                int byteRead;
                while ((byteRead = stream.read(buffer)) != -1) {
                    fs.write(buffer, 0, byteRead);
                }
            }catch (IOException e){
                throw new RuntimeException("创建文件失败");
            }finally {
                try {
                    if (fs != null) {
                        fs.flush();
                        fs.close();
                    }
                }catch (IOException e){
                    throw new RuntimeException("关闭失败");
                }
                try {
                    if (stream != null) {
                        stream.close();
                    }
                }catch (IOException e){
                    throw new RuntimeException("关闭失败");
                }
            }
        }

        /**
         * 富文本编辑器图片上传
         * @param file
         * @param request
         * @param response
         */

        @RequestMapping("/uploadImg")
        public void uplodaImg(@RequestParam("upload") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
            result=new JSONObject();
            String pathname = "";
            try {
                //得到文件的名称
                String fileName = file.getOriginalFilename();
                PrintWriter out = response.getWriter();
                String proName = request.getContextPath();
                //获得文件的类型  根据文件类型创建文件夹
                String fileType = file.getContentType().split("/")[0];
                fileType = "image,audio,video".contains(fileType) ? fileType : "file";
                String rootPath = configureProperties.getFileUploadPath();


                String uploadContentType = file.getContentType();
                if (uploadContentType.equals("image/pjpeg") || uploadContentType.equals("image/jpeg")||uploadContentType.equals("image/png") || uploadContentType.equals("image/x-png")||uploadContentType.equals("image/gif")||uploadContentType.equals("image/bmp")) {
                    //获得完整的文件夹
                    String descDirNames = Global.UPLOAD_FILES + fileType + "/" + UserUtils.getUser().getId();

                    FileUtils.createDirectory(rootPath + descDirNames);

                    //文件存在的地址
                    pathname = rootPath + descDirNames + "/" + fileName;

                    //保存文件
                    this.FileInputStream(file.getInputStream(), pathname);
                    result=this.success(1, fileName,  "/"+descDirNames + "/" + fileName, null);
                    out.println(result);
                    return;

                } else {
                    result=this.error(0, "文件格式不正确（必须为.jpg/.gif/.bmp/.png文件）");
                    out.println(result);
                    return;
                }

            } catch (Exception e) {
                e.printStackTrace();
                try {
                    response.getWriter().println(result);
                    return;
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }



        }


        /**
         * 上传失败返回：
         */
        Map<String,Object> msgMap = null;
        public JSONObject error(int code, String msg){
            result=new JSONObject();
            msgMap=new HashMap<>();
            msgMap.put("message",msg);
            result.put("uploaded", code);
            result.put("error", msgMap);
            return result;
        }


        /**
         * 上传成功返回：
         * @param code
         * @param fileName
         * @param url
         * @param msg
         * @return
         */
        public JSONObject success(int code, String fileName,String url,String msg){
            result=new JSONObject();
            msgMap=new HashMap<>();
            if(!StringUtils.isEmpty(msg)){
                msgMap.put("message",msg);
                result.put("error",msgMap);
            }
            result.put("uploaded",code);
            result.put("fileName",fileName);
            result.put("url",url);
            return result;
        }


        /**
         * 判断文件是否存在
         * @param path
         * @return
         */
        public boolean existencefile(String path){
            boolean ison=FileUtils.ExistenceFile(path);
            return ison;
        }

        /**
         *文件存在，生成新的文件名称
         */
        public String rendname(String name,int i){

            String path=pathresult+name.substring(0,name.indexOf("."))+"("+(i+1)+")"+name.substring(name.lastIndexOf("."),name.length());
            return path;
        }


        /**
         * 上传文件的格式
         */
        public  Upload getUpload(File file ){
            Upload upload = new Upload();
       /* upload.setFileType(fileType);
        upload.setFileName(fileName);
        upload.setCode(0);
        upload.setMsg("文件上传成功了");
        upload.setFilePath(descDirNames + "/" + fileName);
        upload.setSize(file.getSize());*/
            return upload;

        }

        /**
         * 访问文件路径
         * */
        @GetMapping(value = "/{filename:.+}")

        public void getFile(@PathVariable String filename,HttpServletRequest request, HttpServletResponse response) {

            String location = Paths.get(configureProperties.getFileUploadPath(), filename).toString();
            File file=new File(location);
            FileUtils.downFile(file,request,response);
        }

}
